import os.path
#coding:utf-8
__author__ = "hzq"
__date__ = "$2011-2-19 20:35:38$"
import hashlib
import urllib

import urllib2
import os

import time
import web
import  re
import cPickle as cP

def md5(str):
    m = hashlib.md5()
    m.update(str)
    return m.hexdigest()

def myMd5(str):
    str = md5(str)
    return md5(str[0:16])
def deurlencode(s):
    return urllib.unquote(s)


def post(url, data):
    req = urllib2.Request(url)
    data = urllib.urlencode(data)
    #enable cookie
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
    response = opener.open(req, data)
    return response.read()

def strip_tags(string, allow=''):
    if allow:
        la = allow.replace(",", "|")
        la = "<(%s)\s*([^<]*)>" % (la, )
        p1 = re.compile(la, re.I)
        string = p1.sub(r'{[{\1 \2>', string)
    pd = re.compile(r'<[^<>]*>')
    string = pd.sub("", string)
    return string.replace("{[{", "<")



class cache:


    def __init__(self, dir):

        self.dir = dir
        if os.path.isdir(self.dir) == False:
            os.makedirs(self.dir)


    def cacheSet(self, obj, names, times):
        
        t = time.time() + times
        data = {"_time":t, "data":obj}

        self.__writeFile(names, data)
        return True
    
    
    
    def __writeFile(self, names, data):
        filename = os.path.normpath(self.dir + '/' + names + '.pys')
        f = open(filename, "wb")
        cP.dump(data, f, True)
        f.close()

    
    def __cacheGet(self, names):
        
        t = time.time()
        filename = os.path.normpath(self.dir + '/' + names + '.pys')

        if os.path.isfile(filename) == False:
            return False
        f = file(filename, 'rb')
        data = cP.load(f)
        f.close()
        if t > data["_time"]:
            os.remove(filename)
            return False
        return data
    def __getitem__(self, names):
        data = self.__cacheGet(names)
        if data == False:
            return  False

        return data["data"]

    def __delitem__(self, names):

        os.remove(os.path.normpath(self.dir + '/' + names + '.pys'))

    def __setitem__(self, names, obj):
        data = self.__cacheGet(names)
        
        data["data"] = obj
        self.__writeFile(names, data)
        return True
        















        


